# -*- encoding: utf-8 -*-

"""
@File:      tc_libtdb_libtdb_func_001.py.py
@Time:      2024/04/16 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtdb_libtdb_func_001.py.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtdb libtdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >ltdb_test1.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <tdb.h>
#include <string.h>
#include <fcntl.h>

int main() {
    // 打开一个新的tdb数据库，如果文件不存在则创建
    struct tdb_context *tdb;
    TDB_DATA key, data, result;
    int ret;

    tdb = tdb_open("ltdb_test1.tdb", 0, TDB_DEFAULT, O_CREAT | O_RDWR, 0644);

    if (tdb == NULL) {
        fprintf(stderr, "打开或创建数据库失败\\n");
        return 1;
    }

    // 添加一个新的键值对
    key.dptr = (unsigned char *)"key1";
    key.dsize = strlen("key1") + 1; // 包括空字符
    data.dptr = (unsigned char *)"value1";
    data.dsize = strlen("value1") + 1; // 包括空字符

    ret = tdb_store(tdb, key, data, TDB_REPLACE);
    if (ret != 0) {
        fprintf(stderr, "添加键值对失败\\n");
        tdb_close(tdb);
        return 1;
    }

    // 检索刚才添加的键值对
    result = tdb_fetch(tdb, key);
    if (result.dptr) {
        printf("检索到的值: %s\\n", result.dptr);
        free(result.dptr); // 记得释放检索结果占用的内存
    } else {
        fprintf(stderr, "键值对检索失败\\n");
    }

    // 更新此键的值
    data.dptr = (unsigned char *)"value2";
    data.dsize = strlen("value2") + 1;
    ret = tdb_store(tdb, key, data, TDB_REPLACE);
    if (ret == 0) {
        printf("值更新成功。\\n");
    } else {
        fprintf(stderr, "值更新失败。\\n");
    }

    // 再次检索以验证更新
    result = tdb_fetch(tdb, key);
    if (result.dptr) {
        printf("更新后的值: %s\\n", result.dptr);
        free(result.dptr);
    } else {
        fprintf(stderr, "键值对检索失败\\n");
    }

    // 删除键值对
    ret = tdb_delete(tdb, key);
    if (ret == 0) {
        printf("键值对删除成功。\\n");
    } else {
        fprintf(stderr, "键值对删除失败。\\n");
    }

    // 关闭数据库
    tdb_close(tdb);

    printf("所有操作执行完毕\\n");
    
    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o ltdb_test1 ltdb_test1.c -ltdb")
        code, ltdb_result = self.cmd("./ltdb_test1")
        self.assertIn('所有操作执行完毕', ltdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf ltdb_test1.c ltdb_test1 ltdb_test1.tdb")
